package com.xiaolei.fastnio.http

import com.xiaolei.fastnio.http.Adapter.HttpClientAdapterFactory
import com.xiaolei.fastnio.http.Comm.ContentType
import com.xiaolei.fastnio.http.Comm.RequestMethod
import com.xiaolei.fastnio.library.NioServer
import java.io.File
import java.lang.RuntimeException

/**
 * 处理类
 */
typealias onRoute = (request: Request, response: Response) -> Unit

class Route(var method: RequestMethod, val onRoute: onRoute)

/**
 * 所有的请求所产生的临时文件存储的位置
 */
var requestBodyFileDir = File("")

/**
 * http的工作入口
 */
fun http(func: HTTP.() -> Unit)
{
    val http = HTTP()
    http.func()
    NioServer.setPort(http.port)
            .setClientAdapterFactory(http.factory)
            .start()

}

/**
 * 为http所需数据提供类
 */
class HTTP
{
    val factory = HttpClientAdapterFactory()

    var port = 8080

    /**
     * 设置GET请求路由
     */
    fun get(uri: String, route: onRoute) = factory.registerRoute(uri, RequestMethod.GET, route = route)

    /**
     * 设置POST请求路由
     */
    fun post(uri: String, route: onRoute) = factory.registerRoute(uri, RequestMethod.POST, route = route)

    /**
     * 设置静态文件
     */
    fun static(dir: File, rootFile: File = dir)
    {
        if (dir.exists() && dir.isDirectory)
        {
            val files = dir.listFiles() ?: return
            for (file in files)
            {
                if (file.isDirectory)
                {
                    static(file, rootFile)
                } else
                {
                    val uri = file.absolutePath.replace(rootFile.absolutePath, "")
                    get(uri) { _, response ->
                        response.writeStream(file)
                    }
                }
            }
        } else
        {
            throw RuntimeException("设置的静态文件夹不存在，或者不是文件夹")
        }
    }

    /**
     * 设置静态文件
     */
    fun static(dir: String) = static(File(dir))

    /**
     * 设置首页URI
     */
    fun setIndex(uri: String)
    {
        factory.indexUri = uri
    }

    var tempDir: File
        set(value)
        {
            requestBodyFileDir = value
        }
        get() = requestBodyFileDir
}